import * as THREE from "../lib/three.module.js";

export const getFitScaleValue = function (obj) {
  const boxHelper = new THREE.BoxHelper(obj);
  boxHelper.geometry.computeBoundingBox();
  const box = boxHelper.geometry.boundingBox;
  const maxDiameter = Math.max(
    box.max.x - box.min.x,
    box.max.y - box.min.y,
    box.max.z - box.min.z
  );
  return this.camera.position.z / (maxDiameter * 2);
};

// 自适应大小, 防止模型过大导致相机处在模型内部
export const setScaleToFitSize = function (obj = this.modelObject) {
  const scaleValue = this.getFitScaleValue(obj);
  obj.scale.set(scaleValue, scaleValue, scaleValue);
  return scaleValue;
};

// 自适应坐标, 是模型始终紧贴在地面上部
export const setPositionToFitGrid = function (obj = this.modelObject) {
  const boxHelper = new THREE.BoxHelper(obj);
  boxHelper.geometry.computeBoundingBox();
  const box = boxHelper.geometry.boundingBox;
  const girdPositionY = this.scene.position.y;
  const boxMinYPosition = box.min.y;
  if (boxMinYPosition < 0) {
    obj.position.set(obj.position.x, Math.abs(girdPositionY - boxMinYPosition), obj.position.z);
  } else {
    obj.position.set(obj.position.x, 0, obj.position.z);
  }
};

// 解决3D-MAX等软件导出模型后Z轴朝上的问题, 自动调成Y轴朝上
export const setAxisDirection = function (objTree) {
  const { GlobalSettings: { UpAxis: { value } } } = objTree;
  if (value === 2) {
    this.modelObject.rotation.set(300, 0, 0);
  }
};